#!/usr/bin/env python3
"""
libesmtp MCP Server

面向 libesmtp 软件的命令行操作封装，提供以下 MCP tools：

1. libesmtp_compile_test - 编译 libesmtp 相关的 C 程序文件
   用途：使用 gcc 编译包含 libesmtp 库的 C 程序
   参数：source_file (str): C 源文件路径, output_file (str): 输出可执行文件路径
   返回：{"success": bool, "command": str, "exit_code": int, "stdout": str, "stderr": str}

2. libesmtp_sendmail_test - 测试 libesmtp 邮件发送功能
   用途：创建测试邮件并执行 sendmail 程序验证邮件传输功能
   参数：mail_content (str): 邮件内容, mail_file (str): 邮件文件路径, sendmail_path (str): sendmail 程序路径
   返回：{"success": bool, "command": str, "exit_code": int, "stdout": str, "stderr": str}
"""

import subprocess
import os
from typing import List
from mcp.server.fastmcp import FastMCP, Context

mcp = FastMCP("libesmtp MCP Server")

@mcp.tool()
def libesmtp_compile_test(source_file: str, output_file: str) -> dict:
    """
    编译 libesmtp 相关的 C 程序文件
    
    参数:
        source_file: C 源文件路径
        output_file: 编译输出的可执行文件路径
        
    返回 JSON 结构:
        {
            "success": bool,      # 命令是否成功执行
            "command": str,       # 执行的完整命令
            "exit_code": int,     # 命令退出码
            "stdout": str,        # 标准输出内容
            "stderr": str         # 标准错误内容
        }
    """
    try:
        # 获取 libesmtp 编译标志
        cflags_cmd = ["libesmtp-config", "--cflags"]
        cflags_result = subprocess.run(cflags_cmd, capture_output=True, text=True)
        
        if cflags_result.returncode != 0:
            return {
                "success": False,
                "command": " ".join(cflags_cmd),
                "exit_code": cflags_result.returncode,
                "stdout": cflags_result.stdout,
                "stderr": cflags_result.stderr
            }
        
        cflags = cflags_result.stdout.strip()
        
        # 编译命令
        compile_cmd = [
            "gcc", "-std=c99", "-Wall",
            cflags,
            "-o", output_file,
            source_file,
            "-lesmtp"
        ]
        
        result = subprocess.run(compile_cmd, capture_output=True, text=True)
        
        return {
            "success": result.returncode == 0,
            "command": " ".join(compile_cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
        
    except Exception as e:
        return {
            "success": False,
            "command": f"gcc compilation with libesmtp",
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def libesmtp_sendmail_test(mail_content: str = "test", mail_file: str = "test-mail.eml", sendmail_path: str = "./sendmail") -> dict:
    """
    测试 libesmtp 邮件发送功能
    
    参数:
        mail_content: 邮件内容文本
        mail_file: 邮件文件保存路径
        sendmail_path: sendmail 可执行程序路径
        
    返回 JSON 结构:
        {
            "success": bool,      # 命令是否成功执行
            "command": str,       # 执行的完整命令
            "exit_code": int,     # 命令退出码
            "stdout": str,        # 标准输出内容
            "stderr": str         # 标准错误内容
        }
    """
    try:
        # 创建邮件文件
        with open(mail_file, 'w') as f:
            f.write(mail_content)
        
        # 启动 postfix 服务
        start_postfix_cmd = ["systemctl", "start", "postfix"]
        postfix_result = subprocess.run(start_postfix_cmd, capture_output=True, text=True)
        
        if postfix_result.returncode != 0:
            return {
                "success": False,
                "command": " ".join(start_postfix_cmd),
                "exit_code": postfix_result.returncode,
                "stdout": postfix_result.stdout,
                "stderr": postfix_result.stderr
            }
        
        # 执行 sendmail 程序
        sendmail_cmd = [sendmail_path]
        result = subprocess.run(sendmail_cmd, capture_output=True, text=True)
        
        return {
            "success": result.returncode == 0,
            "command": " ".join(sendmail_cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
        
    except Exception as e:
        return {
            "success": False,
            "command": f"sendmail test execution",
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

if __name__ == "__main__":
    mcp.run()